<?php

namespace App\Http\Controllers;

use App\Helpers\Tools;
use App\Models\AdvertisAnalyzes;
use App\Models\AdvertisPositions;
use App\Models\Draws;
use App\Models\PrizeDraw;
use App\Models\VisitorRecord;
use App\Models\Adverti;
use Illuminate\Support\Facades\Redis;
use App\Http\Resources\AdvertisPositions as AdvertisPositionsResource;

class AdvertiController extends ApiController
{
    /**
     * 用户抽奖
     * @param int $id 广告位id
     * @param string $advertiIdList 抽中过的广告id列表
     * @param int $system 抽中的手机系统
     * @param int $drawNum 查看用户是第几次抽奖
     * @param string $city 用户所在城市
     *
     * @author 日隆
     *
     * @return $resource
     */
    public function draw($id)
    {
        $advertiIdList = explode(',', request('advertiIdList'), 0);
        $system = request('system');
        $city = session()->get('city');
        $n = 0; // 中奖概率总和
        $arr = []; // 数组
        $arr2 = []; // 广告id数组
        $adverti = []; // 广告数组
        $bliling = request('bliling');

        // 获取该广告位的奖券id
        $advertisPositions = $this->advertisPositions($id)->toArray();
        $advertiList = $advertisPositions['advertis'];
        $drawNum = $advertisPositions['activities']['count'] - request('drawNum');

        foreach ($advertiList as $key => $val) {

            // 判断该优惠券有没定向系统
            $system_list = explode(',', $val['put_system']);
            if (!in_array('1', $system_list) && !in_array($system, $system_list)) {
                // 如果不是所有的系统都使用的优惠券并且不符合系统的优惠券直接跳出
                continue;
            }

            // 判断该优惠券有没定向城市
            if ($val['put_city'] != '' && $city != '') {
                // 优惠券定向的城市
                $couponCity = explode(';', $val['put_city']);

                // 查出用户省市
                $province_city = explode('省', $city);

                if (count($province_city) > 1) {
                    // 非直辖市
                    $is_province = $province_city[0] . '省';
                    $is_city = explode('市', $province_city[1])[0];

                    if (!in_array($is_province, $couponCity) && !in_array($is_city, $couponCity)) {
                        continue;
                    }
                } else {
                    // 直辖市
                    $is_city = explode('市', $province_city[0])[0];

                    if (!in_array($is_city, $couponCity)) {
                        continue;
                    }
                }

            }

            // 中奖概率最大值
            $n += $val['odds'];

            // 中奖数组分位
            $arr[$key] = $n;
        }

        // 如果没有已经定位好的位置，则使用下面的
        if (!$adverti) {
            // 生成随机数
            $i = rand(1, $n);

            // 对比，看数字在哪个区间,然后获取该数组
            foreach ($arr as $key => $val) {
                if ($i <= $val) {
                    $adverti = $advertiList[$key];
                    break;
                }
            }
        }

        session()->put('activitiesId', $advertisPositions['activities_id']);
        session()->put('positionId', $id);
        session()->put('mediaId', $advertisPositions['activities']['media_id']);

        // 插入抽奖记录表
        //$drawId = $this->addDraw($adverti['id']);

        //$adverti['draw_id'] = $drawId;

        // 判断是否等于2
        if($adverti['bliling'] == 2) {
            session()->put('isBliling', '1');
        }

        $resource = Tools::setData($adverti);

        return $resource;
    }

    /**
     * 返回广告位详情
     * @param int $id 广告位id
     * @param array $data 存入访客表数组
     *
     * @author 日隆
     *
     * @return $resource
     */
    public function info($id)
    {
        // 获取活动信息
        $info = $this->advertisPositions($id);

        // 添加访问记录
        $data = request()->only(['src', 'is_new', 'entrance']);
        $data['activity_id'] = $info->activities->id;
        $data['position_id'] = $id;
        $data['media_id'] = $info->media_id;
        $this->addRecord($data);

        $resource = new AdvertisPositionsResource($info);

        return $resource;
    }

    /**
     * 获取历史奖品
     * @param int $id 广告位id
     *
     * @author 日隆
     *
     * @return $resource
     */
    public function prizeHistory()
    {
        $prizeHistory = json_decode(request('prizeHistory'));

        // TODO 放弃优化版，后续回来调
        /*$list = $this->advertisPositions($id)->advertis;

        $prizeList = [];
        foreach ($prizeHistory as $key => $val) {
            foreach ($list as $k => $v) {

                if ($val == $v->id) {
                    $v->prize_id = $key;
                    $prizeList[$key] = $v;
                    break;
                }
            }
        }*/

        $prizeList = [];
        foreach ($prizeHistory as $key => $val) {
            $prizeList[$key] = \App\Models\Adverti::find($val);
            $prizeList[$key]['prize_id'] = $key;

            $prizeList[$key]['endtime'] = explode(' ', $prizeList[$key]->endtime)[0];
        }

        $resource = Tools::setData(array_reverse($prizeList));

        return $resource;
    }

    /**
     * 使用奖品登记
     * @param int $id
     *
     * @author 日隆
     *
     * @return $resource
     */
    public function useDraw($id)
    {
        $draw = Draws::find($id);
        $draw->status = 1;
        $draw->save();

        return Tools::setData([]);
    }

    /**
     * 广告位点击登记
     * @param int $id
     *
     * @author 日隆
     *
     * @return $resource
     */
    public function recordPositionAdverti($id)
    {
        $resource = $this->addDraw($id, 1);

        if($resource) {
            return Tools::success($resource);
        } else {
            return Tools::error('添加失败');
        }

    }

    /**
     * 查询广告位详情
     * @param int $id 广告位id
     *
     * @author 日隆
     *
     * @return $resource
     */
    protected function advertisPositions($id)
    {
        $time = time();
        if ($time - Redis::hget("position:info:$id", 'updateTime') > 100000) {
            $info = AdvertisPositions::with(['advertis' => function ($query) {
                return $query->where('switch', '1')->orderBy('odds', 'asc');
            }, 'activities', 'position' => function ($query) {
                return $query->where('switch', '1')->orderBy('times', 'asc');
            }])->find($id);

            Redis::hset("position:info:$id", 'updateTime', $time);
            Redis::hset("position:info:$id", 'info', serialize($info));
        } else {
            $info = unserialize(Redis::hget("position:info:$id", 'info'));
        }

        return $info;
    }

    /**
     * 添加访问记录
     * @param int $id 广告位id
     * @param int $is_new 是否新访客
     * @param string $src 来源src
     *
     * @author 日隆
     *
     * @return array
     */
    protected function addRecord($data)
    {
        $dataAddress = $this->getAddress();
        $data['day'] = date('Y-m-d');
        $data['cookie'] = session()->getId();
        $data['ip'] = $dataAddress['ip'];
        $city = $dataAddress['city'] ?? '';
        $province = $dataAddress['province'] ?? '';
        $data['city'] = $province . '省' . $city . '市';

        session()->put('city', $data['city']);
        $visitorRecord = new VisitorRecord;
        $visitorRecord->fill($data);

        $id = $visitorRecord->save();
        $data['id'] = $id;

        return $data;
    }

    /**
     * 根据ip地址获取详细信息
     *
     * @author 日隆
     *
     */
    protected function getAddress()
    {
        $ip = $this->getIp();
        $url = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip;

        $getData = @file_get_contents($url);
        $getData = explode('=', $getData);

        $data = json_decode(substr($getData[1] ?? '', 0, strlen($getData[1] ?? '') - 1), true);

        $data['ip'] = $ip;
        return $data;
    }

    /**
     * 获取用户真实ip
     *
     * @author 日隆
     *
     */
    protected function getIp()
    {
        $ip = !empty($_SERVER['HTTP_CLIENT_IP']) ? $_SERVER['HTTP_CLIENT_IP'] : (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : (!empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'unknown'));
        return $ip;
    }

    /**
     * 添加进抽奖记录表
     * @param int $activityId 活动id
     * @param int $source 类型，0为抽奖，1为广告位点击
     *
     * @author 日隆
     * @return $id
     */
    protected function addDraw($advertiId, $source = 0)
    {
        $data['id'] = $this->sendDrawId();
        $data['position_id'] = session()->get('positionId');;
        $data['media_id'] = session()->get('mediaId');;
        $data['activity_id'] = session()->get('activitiesId');
        $data['adverti_id'] = $advertiId;
        $data['day'] = date('Y-m-d');
        $data['ip'] = $this->getIp();
        $data['cookie'] = session()->getId();

        if ($source == 0) {
            $object = new Draws;
        } elseif ($source == 1) {
            $object = new AdvertisAnalyzes;
        }

        $object->fill($data);

        $object->save();

        return $object->id;
    }

    /**
     * 抽奖记录id发射器
     *
     * @author 日隆
     * @return $id
     */
    protected function sendDrawId()
    {
        if (Redis::exists('draw:id')) {
            Redis::incr('draw:id');
            return Redis::get('draw:id');
        } else {
            $id = Draws::max('id');
            ++$id;
            Redis::set('draw:id', $id);
            return $id;
        }
    }

    /**
     * 统计页面跳转数据
     *
     * @author 日隆
     */
    public function analyze($id)
    {
        // 添加pv统计数据
        Redis::zincrby("analyze:position:$id", 1, date('Y-m-d'));

        // 添加uv统计数据
        if (!session()->get('isUv')) {
            session()->put('isUv', 1);
            Redis::zincrby("analyze:position:$id", 1, date('Y-m-d') . ':uv');
        }

        // 跳转地址
        $fileName = request('fn');
        $src = request('src');
        $url = "https://game.bestpeng.com:92/$fileName.html?id=$id&src=$src";

        header("Location: $url");
    }

    /**
     * 中奖登记
     * @param int $activities_id 活动id
     * @param int $adverti_id 奖券id
     * @param int $nickname 姓名
     * @param string $mobile 电话
     * @param string $address 地址
     *
     * @author 日隆
     * @return $id
     */
    public function apply()
    {
        // 获取数组
        $data = request()->only('activities_id', 'adverti_id', 'nickname', 'mobile', 'address');

        // 判断消耗是否已满
        $prizeDraw = new PrizeDraw();
        $prizeDraw->fill($data);
        $res = $prizeDraw->save();

        if ($res) {
            return Tools::success();
        } else {
            return Tools::error('入库失败');
        }
    }

    /**
     * 获取单条广告信息
     * @param int $adverti_id 奖券id
     *
     * @author 日隆
     * @return $info
     */
    protected function advertiInfo($id)
    {
        $time = time();
        if ($time - Redis::hget("adverti:info:$id", 'updateTime') > 20) {
            $info = Adverti::find($id);

            Redis::hset("adverti:info:$id", 'updateTime', $time);
            Redis::hset("adverti:info:$id", 'info', serialize($info));
            Redis::hset("adverti:info:$id", 'budget', $info->day_budget);
        } else {
            $info = unserialize(Redis::hget("adverti:info:$id", 'info'));
        }

        return $info;
    }

    /**
     *
     * @param int $adverti_id 奖券id
     *
     * @author 日隆
     * @return $adverti
     */
    protected function places($id)
    {
        // 日后将缓存数据添加进表单和修改提交事件里
        $this->advertiInfo($id);

        // 先添加消耗
        $day = date('Y-m-d');
        $useBudget = Redis::hincrby("adverti:info:$id", "$day:useBudget", 1);

        $budget = Redis::hget("adverti:info:$id", 'budget');

        if ($useBudget < $budget) {
            return true;
        } else {
            return false;
        }
    }
}
